package com.dz.risk.aspect;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dz.risk.exception.VerifyException;
import com.dz.risk.pojo.domain.ConfigEntity;
import com.dz.risk.service.ConfigService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * 配置字典切面处理类
 *
 * @author Doke
 * @date 2021/9/10 8:53
 */
@Component
@Aspect
public class ConfigAop {

    private final ConfigService configService;

    @Autowired
    public ConfigAop(ConfigService configService) {
        this.configService = configService;
    }

    /**
     * 验证配置项类别是否已存在
     *
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.dz.risk.service.impl.ConfigServiceImpl.addConfigType(..))")
    public Object checkAddConfigType(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        ConfigEntity configEntity = (ConfigEntity) args[0];

        QueryWrapper<ConfigEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(ConfigEntity::getConfigType, configEntity.getConfigType())
                .or()
                .eq(ConfigEntity::getConfigTypeCode, configEntity.getConfigTypeCode());
        List<ConfigEntity> list = configService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            throw new VerifyException("配置项或编码已存在");
        }
        return point.proceed();
    }

    /**
     * 验证配置项类别是否已存在
     *
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.dz.risk.service.ConfigService.save(..)) || execution(* com.dz.risk.service.ConfigService.updateById(..))")
    public Object checkAdd(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        ConfigEntity configEntity = (ConfigEntity) args[0];
        QueryWrapper<ConfigEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(ConfigEntity::getConfigType, configEntity.getConfigType())
                .eq(ConfigEntity::getConfigName, configEntity.getConfigName())
                .ne(Objects.nonNull(configEntity.getId()), ConfigEntity::getId, configEntity.getId());
        List<ConfigEntity> list = configService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            throw new VerifyException("该配置已存在");
        }
        return point.proceed();
    }
}
